﻿package cn.poco.pepsi.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.location.Criteria;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import cn.poco.pepsi.constants.Constants;

public class GpsLocationUtil {
	
	private LocationManager locationManager;
	private static GpsListener	gpslistener;
	private Context context;
	private static GpsLocationUtil gpslocationutil;
	private HandlerThread handlerThread;
	private Handler myHandler;
	private String lat = "";
	private String lon = "";
	private Runnable run;
	

	private  GpsLocationUtil(Context context) {
		this.context = context;
		handlerThread = new HandlerThread("thread001");
		handlerThread.start();
		myHandler = new Handler(handlerThread.getLooper());
	}
	
	public static GpsLocationUtil getInstance(Context context){
		if(gpslocationutil==null){
			gpslocationutil = new GpsLocationUtil(context);
		}
		return gpslocationutil;
	}
	

	//获取GPS Location
	public void getLocation(final Handler handler) {
		
		// 获取经纬度
		if(locationManager==null)
			locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Criteria criteria = new Criteria();
			//获得最好的定位效果
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			//使用省电模式
			criteria.setPowerRequirement(Criteria.POWER_LOW);
			//获得当前位置提供者
			String provider = locationManager.getBestProvider(criteria, true);
				//注册GPS监听器
				if(gpslistener==null){
					gpslistener  = new GpsListener(handler);
				}
				locationManager.requestLocationUpdates(provider,2000, 10, gpslistener);
				myHandler.post(new myLocation(handler));
				run = new Runnable() {
					@Override
					public void run() {
						if(Constants.GPS_LAT_DATA.equals("") 
								&& Constants.GPS_LON_DATA.equals("")
								&& lat.equals("") && lon.equals("")){
							unRequestListener();
							handler.sendEmptyMessage(Constants.STOP_GPS);
							
						}	
					}
				};
				myHandler.postDelayed(run, 2000 * 10);
		}else{
			handler.sendEmptyMessage(Constants.NO_GPS);
		}

	}
	
	//通过基站定位获取坐标
	private final class myLocation implements Runnable{
		private Handler currHandler;
		public myLocation(Handler handler){
			this.currHandler = handler;
		}
		@Override
		public void run() {
			try {
			if(gpslistener!=null){
			//	unRequestListener();	//取消gps监听
				TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
				GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
				int cid = gcl.getCid();
				int lac = gcl.getLac();
				
				int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0,3));
				int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3,5));
				
					// 组装JSON查询字符串
					JSONObject holder = new JSONObject();
					holder.put("version", "1.1.0");
					holder.put("host", "maps.google.com");
					// holder.put("address_language", "zh_CN");
					holder.put("request_address", true);

					JSONArray array = new JSONArray();
					JSONObject data = new JSONObject();
					data.put("cell_id", cid); // 25070
					data.put("location_area_code", lac);// 4474
					data.put("mobile_country_code", mcc);// 460
					data.put("mobile_network_code", mnc);// 0
					array.put(data);
					holder.put("cell_towers", array);

					// 创建连接，发送请求并接受回应
					DefaultHttpClient client = new DefaultHttpClient();

					HttpPost post = new HttpPost(
							"http://www.google.com/loc/json");

					StringEntity se = new StringEntity(holder.toString());

					post.setEntity(se);
					HttpResponse resp = client.execute(post);

					HttpEntity entity = resp.getEntity();

					BufferedReader br = new BufferedReader(
							new InputStreamReader(entity.getContent()));
					StringBuffer sb = new StringBuffer();
					String result = br.readLine();

					while (result != null) {
						sb.append(result);
						result = br.readLine();
					}
					JSONObject json = new JSONObject(sb.toString());
					JSONObject jsonstr = new JSONObject(json.getString("location"));
					lat = jsonstr.getString("latitude");
					lon = jsonstr.getString("longitude");
					if(!lat.equals("")  && !lon.equals("")){
						currHandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								SendLocationMessage(lat,lon);
								
							}
						}, 1000 * 6);
					}
					
				
			}

			} catch (Exception e) {
				//unRequestListener();
				Log.e("GPSERROR", e.toString());
				//currHandler.sendEmptyMessage(Constants.STOP_GPS);
			}

		
		}
		//发送基站定位信息
		private void SendLocationMessage(String lat, String lon) {
			if(gpslistener!=null){
				Message msg = new Message();
				if(lat!=null && !lat.equals("")&& lon!=null && !lon.equals("")){
					msg.what = Constants.GPS_LOCATION_CHANGE;
					Bundle bundle  = new Bundle();
					bundle.putDouble(Constants.GPS_LAT, Double.parseDouble(lat));
					bundle.putDouble(Constants.GPS_LONG, Double.parseDouble(lon));
					msg.setData(bundle);
					currHandler.sendMessage(msg);
				}else{
					msg.what = Constants.STOP_GPS;
				}
			}
			
		}
		
	}
	
	
	//取消注册GPS监听器
	public void unRequestListener(){
		if(gpslistener!=null){
			locationManager.removeUpdates(gpslistener);
		}
			myHandler.removeCallbacks(run);
			gpslistener = null;
	}
	
	
}
